<template>
  <div class="group-container">
    <!-- 标题和操作按钮 -->
    <div class="header">
      <div class="title">
        <el-icon><UserGroup /></el-icon>
        <h2>组团管理</h2>
      </div>
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>新增组团
      </el-button>
    </div>

    <!-- 搜索栏 -->
    <div class="search-container">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <div class="form-item-group">
          <el-form-item label="组团名称">
            <el-input
                v-model="searchForm.groupName"
                placeholder="请输入组团名称"
                clearable
                prefix-icon="Search"
            />
          </el-form-item>
          <el-form-item label="组团状态">
            <el-select
                v-model="searchForm.groupStatus"
                placeholder="请选择状态"
                clearable
                style="width: 160px"
            >
              <el-option label="进行中" value="进行中" />
              <el-option label="已结束" value="已结束" />
            </el-select>
          </el-form-item>
          <el-form-item label="组团类型">
            <el-select
                v-model="searchForm.groupType"
                placeholder="请选择类型"
                clearable
                style="width: 160px"
            >
              <el-option label="系统活动团" value="系统活动团" />
              <el-option label="个人团" value="个人团" />
            </el-select>
          </el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>查询
          </el-button>
        </div>
        <div class="button-group">
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>重置
          </el-button>
        </div>
      </el-form>
    </div>

    <div class="table-container">
      <el-table :data="tableData" border stripe>
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="groupName" label="组团名称" />
        <el-table-column prop="groupType" label="组团类型" />
        <el-table-column prop="timePeriod" label="组团周期" />
        <el-table-column prop="participantsCount" label="参团人数" width="100" />
        <el-table-column prop="groupStatus" label="组团状态">
          <template #default="{ row }">
            <el-tag :type="row.groupStatus === '进行中' ? 'success' : 'info'">
              {{ row.groupStatus }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="publishTime" label="发布时间" :formatter="formatDate" />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">
              <el-icon><Edit /></el-icon>编辑
            </el-button>
            <el-button
                v-if="row.groupStatus === '已结束'"
                type="success"
                link
                @click="handlePublish(row)"
            >
              <el-icon><Upload /></el-icon>发布
            </el-button>
            <el-button
                v-if="row.groupStatus === '进行中'"
                type="warning"
                link
                @click="handleRecycle(row)"
            >
              <el-icon><Switch /></el-icon>回收
            </el-button>
            <el-button type="danger" link @click="handleDelete(row)">
              <el-icon><Delete /></el-icon>删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
        :title="dialogTitle"
        v-model="dialogVisible"
        width="600px"
        :close-on-click-modal="false"
    >
      <el-form
          ref="formRef"
          :model="formData"
          :rules="formRules"
          label-width="100px"
      >
        <el-form-item label="组团名称" prop="groupName">
          <el-input v-model="formData.groupName" placeholder="请输入组团名称" />
        </el-form-item>
        <el-form-item label="组团类型" prop="groupType">
          <el-select v-model="formData.groupType" placeholder="请选择类型" style="width: 100%">
            <el-option label="系统活动团" value="系统活动团" />
            <el-option label="个人团" value="个人团" />
          </el-select>
        </el-form-item>
        <!-- 开始时间 -->
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
              v-model="formData.startTime"
              type="datetime"
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="选择开始时间"
              style="width: 100%"
          />
        </el-form-item>
        <!-- 结束时间 -->
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
              v-model="formData.endTime"
              type="datetime"
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="选择结束时间"
              style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="参与人数" prop="participantsCount">
          <el-input-number v-model="formData.participantsCount" :min="1" style="width: 100%" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {  Plus, Search, Refresh, Edit, Delete, Switch ,Upload} from '@element-plus/icons-vue'
import axios from 'axios'

// 数据定义
const searchForm = ref({
  groupName: '',
  groupStatus: '',
  groupType: ''
})

const tableData = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const dialogVisible = ref(false)
const dialogTitle = ref('新增组团')
const formRef = ref(null)

const formData = ref({
  id: '',
  groupName: '',
  groupType: '',
  startTime: '',
  endTime: '',
  participantsCount: 1
})

const formRules = {
  groupName: [{ required: true, message: '请输入组团名称', trigger: 'blur' }],
  groupType: [{ required: true, message: '请选择组团类型', trigger: 'change' }],
  startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
  endTime: [{ required: true, message: '请选择结束时间', trigger: 'change' }],
  participantsCount: [{ required: true, message: '请输入参与人数', trigger: 'blur' }]
}

// 获取数据
const fetchData = async () => {
  try {
    const { data } = await axios.get('/groupInfo/getGroupInfoByPage', {
      params: {
        page: currentPage.value,
        size: pageSize.value,
        groupName: searchForm.value.groupName,
        groupStatus: searchForm.value.groupStatus,
        groupType: searchForm.value.groupType
      }
    })
    tableData.value = data.records
    total.value = data.total
  } catch (error) {
    ElMessage.error('获取数据失败')
  }
}
const handlePublish = (row) => {
  ElMessageBox.confirm('确认发布该组团?', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      await axios.put(`/groupInfo/publish?id=${row.id}`)
      ElMessage.success('发布成功')
      fetchData()
    } catch (error) {
      ElMessage.error('发布失败')
    }
  })
}
// 事件处理
const handleSearch = () => {
  currentPage.value = 1
  fetchData()
}

const resetSearch = () => {
  searchForm.value = {
    groupName: '',
    groupStatus: '',
    groupType: ''
  }
  handleSearch()
}

const handleAdd = () => {
  dialogTitle.value = '新增组团'
  formData.value = {
    id: '',
    groupName: '',
    groupType: '',
    startTime: '',
    endTime: '',
    participantsCount: 1
  }
  dialogVisible.value = true
}

const handleEdit = (row) => {
  dialogTitle.value = '编辑组团'
  formData.value = { ...row }
  dialogVisible.value = true
}

const handleSave = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()

    if (formData.value.id) {
      await axios.put('/groupInfo/updateGroupInfo', formData.value)
      ElMessage.success('更新成功')
    } else {
      await axios.post('/groupInfo/addGroupInfo', formData.value)
      ElMessage.success('添加成功')
    }

    dialogVisible.value = false
    fetchData()
  } catch (error) {
    ElMessage.error('保存失败')
  }
}

const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该组团?', '警告', {
    type: 'warning'
  }).then(async () => {
    try {
      await axios.delete(`/groupInfo/deleteGroupInfo?id=${row.id}`)
      ElMessage.success('删除成功')
      fetchData()
    } catch (error) {
      ElMessage.error('删除失败')
    }
  })
}

const handleRecycle = (row) => {
  ElMessageBox.confirm('确认回收该组团?', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      await axios.put(`/groupInfo/recycleGroupInfo?id=${row.id}`)
      ElMessage.success('回收成功')
      fetchData()
    } catch (error) {
      ElMessage.error('回收失败')
    }
  })
}

const handleSizeChange = (val) => {
  pageSize.value = val
  fetchData()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchData()
}

const formatDate = (row, column, cellValue) => {
  if (!cellValue) return ''
  return new Date(cellValue).toLocaleString()
}

onMounted(() => {
  fetchData()
})
</script>

<style scoped>
/* 容器基础样式 */
.group-container {
  padding: 24px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 48px);
}

/* 头部样式 */
.header {
  margin-bottom: 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #fff;
  padding: 16px 24px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.header .title {
  display: flex;
  align-items: center;
  gap: 8px;
}

.header .title h2 {
  margin: 0;
  font-size: 20px;
  color: #303133;
}

/* 搜索区域样式 */
.search-container {
  margin-bottom: 24px;
  background-color: #fff;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.search-form {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.form-item-group {
  display: flex;
  align-items: center;
  gap: 16px;
  flex-wrap: wrap;
  flex: 1;
}

.button-group {
  display: flex;
  gap: 8px;
  align-items: center;
  white-space: nowrap;
}

/* 表格区域样式 */
.table-container {
  background-color: #fff;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  margin-bottom: 24px;
}

/* 分页区域样式 */
.pagination-container {
  background-color: #fff;
  padding: 16px 24px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  display: flex;
  justify-content: flex-end;
}

/* 响应式布局 */
@media screen and (max-width: 768px) {
  .search-form {
    flex-direction: column;
    align-items: stretch;
  }

  .form-item-group {
    flex-direction: column;
    width: 100%;
  }

  .button-group {
    width: 100%;
    justify-content: flex-end;
    margin-top: 16px;
  }

  :deep(.el-form-item) {
    margin-right: 0;
    width: 100%;
  }
}

/* 通用样式调整 */
:deep(.el-form-item) {
  margin-bottom: 0;
  margin-right: 0;
}

:deep(.el-form-item__content) {
  flex-wrap: nowrap;
}
</style>